<?php
namespace app\models;
use ac\component\tool\Tool;

use Yii;

class AdminRole extends Basic
{
    
    public static function tableName()
    {
        return '{{%admin_role}}';
    }

    public function rules()
    {
        return [
            ['rolename', 'required', 'message' => 'rolename不能为空', 'on' => 'add'],
            ['rolename', 'string', 'message' => 'rolename必须是字符串',
                         'min' => 2, 'tooShort' => 'rolename最短2位',
                         'max' => 32, 'tooLong' => 'rolename最长32位'],
            ['rolename', 'validateRolenameRepeat', 'on' => ['add', 'mod']],
            // ['description', 'default', 'value' => ''],
            ['description', 'string', 'message' => 'description必须是字符串'],
            ['sort', 'integer', 'message' => 'sort必须为数字，或数字字符串', 
                     'min'=>0, 'tooSmall' => 'sort最小存储0', 
                     'max'=>4294967295, 'tooBig' => 'sort最大存储4294967295'],
            // ['display', 'default', 'value' => 1],
            ['display', 'integer', 'message' => 'display必须为数字，或数字字符串'],
            ['display', 'in', 'range' => array(1, 2), 'message' => 'display值必须在1,2中选择'],
        ];
    }


    /*rules 验证名称是否存在*/
    public function validateRolenameRepeat()
    {
        if(!$this->hasErrors()){
            $data = null;
            if($this->scenario == 'add'){
                $data = self::find()
                        ->where('rolename = :rname', [':rname' => $this->rolename])
                        ->one();
            }
            if($this->scenario == 'mod'){
                $data = self::find()
                        ->where('rolename = :rname and role_id != :id', [':rname' => $this->rolename, ':id' => $this->role_id])
                        ->one();
            }
            if(!is_null($data)){
                $this->addError('repeatRolename', '该名称已经存在');
            }
        }
    }


    /*添加角色*/
    public function addAdminRole($data)
    {
        // P($data);
        $this->scenario = 'add';
        if(isset($data['AdminRole']['display'])){
            $data['AdminRole']['display'] = Tool::changeBool($data['AdminRole']['display']);
        }
        if($this->load($data) and $this->validate()){
            if($this->save(false)){
                $role_id = $this->getPrimaryKey();
                $this->updateAll(['sort' => $role_id], 'role_id = :id', [':id' => $role_id]);
                return true;
            }
        }
        return false;
    }

    /*
    修改角色
    $data   修改的数据
    $id     角色ID
    */
    public function modifyAdminRole($data, $id)
    {
        $this->scenario = 'mod';
        if(isset($data['AdminRole']['display'])){
            $data['AdminRole']['display'] = Tool::changeBool($data['AdminRole']['display']);
        }
        $adminRole = AdminRole::find()
                     ->where('role_id = :id', [':id' => $id])
                     ->one();
        if(!is_null($adminRole)){
            if($this->load($data)){
                $this->role_id = $id;
                if($this->validate()){
                    if(isset($this->rolename)){
                        $adminRole->rolename = $this->rolename;
                    }
                    if(isset($this->description)){
                        $adminRole->description = $this->description;
                    }
                    if(isset($this->display)){
                        $adminRole->display = $this->display;
                    }
                    if($adminRole->save(false)){
                        return true;
                    }
                }
            }
        };
        return false;
    }

    /*
    排序
    $sort
    */
    public function setSort($sort)
    {
        $origin = $sort;
        $sort = implode(',', $sort);
        $sql = 'select sort from {{%admin_role}} where find_in_set (role_id, :sort) order by sort desc limit 0, 1';
        //获取 传过来的数据中，在老排序的第一位数据 是当前数据中排序值最大的，
        //当前面没有数据的时候，此最大排序值就是起始值
        $currMaxSort = AdminRole::findBySql($sql, [':sort' => $sort])->one();
        $sql = 'select sort from {{%admin_role}} where sort > (' . $sql . ') order by sort asc limit 0, 1';
        // echo $sql;
        $adminRole = AdminRole::findBySql($sql, [':sort' => $sort])->one();//获取老排序 紧挨着的前一个排序值
        if(is_null($adminRole) or $adminRole->sort == 0){//如果没有 或前一个排序值也0，则从1开始计算
            $sortNum = $currMaxSort->sort+1;
        }else{
            $sortNum = $adminRole->sort;
        }
        // P($sortNum);
        $transaction = Yii::$app->db->beginTransaction();//事物处理
        try{
            foreach($origin as $k => $v){
                $sortNum--;
                $this->updateAll(['sort' => $sortNum], 'role_id = :id', [':id' => $v]);
            }
            $transaction->commit();
            return true;
        }catch(\Exception $exception){
            $transaction->rollback();
        };
        return false;
    }

    
}